//
//  NYSearchViewController.m
//  NiuWaJiaoYu
//
//  Created by MinLison on 2018/1/7.
//  Copyright © 2018年 niuwaketang. All rights reserved.
//

#import "NYSearchViewController.h"
#import "NYHomeViewController.h"
#import "NYSearchListViewController.h"

//views
#import "NYCommonSearchView.h"
#import "NYSearchHistoryCell.h"
#import "NYSearchSectionFooterView.h"
#import "NYSearchHistoryTabSrctionView.h"


//models
#import "NYSearchHistoryModel.h"

// 搜索历史存储路径
#define NYSEARCH_SEARCH_HISTORY_CACHE_PATH [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"NYSearchhistories.plist"]

@interface NYSearchViewController ()  <UISearchBarDelegate, QMUITableViewDelegate>

@property (nonatomic, strong) QMUISearchBar *mySearchBar;
@property (nonatomic, strong) QMUIButton *cancelButton;
// 搜索历史
@property (nonatomic, strong) NSMutableArray *searchMutaHistories;

// 搜索历史缓存保存路径
@property (nonatomic, copy) NSString *searchHistoriesCachePath;
// 搜索历史记录缓存数量，默认为20
@property (nonatomic, assign) NSUInteger searchHistoriesCount;

@end

@implementation NYSearchViewController

#pragma mark - Life Cycle Methods

- (void)viewDidLoad {
    [super viewDidLoad];

    
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self initUI];
}
#pragma mark - Intial Methods
- (void)initUI {
    
    [self configNimbus];
    self.searchHistoriesCount = 20;
    [self configRefreshHistoryData];
}
- (void)initTableView {
    [super initTableView];
    [self.tableView registerClass:[NYSearchHistoryTabSrctionView class] forHeaderFooterViewReuseIdentifier:[NYSearchHistoryTabSrctionView className]];
    [self.tableView registerClass:[NYSearchSectionFooterView class] forHeaderFooterViewReuseIdentifier:[NYSearchSectionFooterView className]];
    
}
- (void)configNimbus {
    [super configNimbus];
    self.tableViewModel.delegate = self;
    
    @weakify(self);
    [self.tableViewActions attachToClass:[NYSearchHistoryModel class] tapBlock:^BOOL(NYSearchHistoryModel *object, id target, NSIndexPath *indexPath) {
        
        @strongify(self);
        NYSearchListViewController *ViewController = [NYSearchListViewController new];
        ViewController.searchString = object.historyString;
        [self.navigationController pushViewController:ViewController animated:true];
        return true;
    }];
}
- (void)configRefreshHistoryData {
    
    [self.tableViewModel removeAll];
    self.searchMutaHistories = nil;
    NSEnumerator *arrayEnumerator = [self.searchMutaHistories objectEnumerator];
    NSString *obj;
    
    NSMutableArray *arrayM = [NSMutableArray array];
    while ((obj = [arrayEnumerator nextObject]) != nil) {
        
        NYSearchHistoryModel *model = [NYSearchHistoryModel new];
        model.historyString = obj;
        [arrayM addObject:model];
    }
    [self.tableViewModel addObjectsFromArray:arrayM];
    [self.tableView reloadData];
}
#pragma mark - Network Methods

#pragma mark - Target Methods
- (void)popViewControllerAction {
    
    [self.navigationController popViewControllerAnimated:true];
//    [self popToControllerClass:[NYHomeViewController class]];
}
- (void)clearRecordEvent:(QMUIButton *)btn {
    // 移除所有历史搜索
    [self.searchMutaHistories removeAllObjects];
    // 移除数据缓存
    [NSKeyedArchiver archiveRootObject:self.searchMutaHistories toFile:self.searchHistoriesCachePath];
    
    [self.tableView reloadData];
    NSLogInfo(@"清除历史纪录");
}

#pragma mark - Public Methods

#pragma mark - Private Method
- (void)configNavigationBar:(BaseNavigationBar *)navigationBar {
    [self.navigationItem setLeftBarButtonItem:nil];
    self.navigationItem.hidesBackButton = true;

    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 65, 28)];
    view.backgroundColor = [UIColor whiteColor];
    view.layer.cornerRadius = 14.f;
    view.clipsToBounds = true;
    [view addSubview:self.mySearchBar];
    [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:self.cancelButton]];
    self.navigationItem.titleView = view;
}
- (UIImage *)navigationBarShadowImage {
    return [[UIImage nav_bar_shadows] qmui_imageWithAlpha:0.8];
}
+ (NYViewControllerNavigationBarType)navigationBarType {
    
    return NYViewControllerNavigationBarTypeBlue;
}

#pragma mark - External Delegate
#pragma mark - QMUITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 35;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 42;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    NYSearchHistoryTabSrctionView *headView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:[NYSearchHistoryTabSrctionView className]];
    headView.title = @"历史搜索";
    return headView;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    NYSearchSectionFooterView *footView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:[NYSearchSectionFooterView className]];
    @weakify(self);
    footView.completeHandle = ^{
        
        @strongify(self);
        // 清除信息
        [self.searchMutaHistories removeAllObjects];
        [NSKeyedArchiver archiveRootObject:self.searchMutaHistories toFile:self.searchHistoriesCachePath];
        [self configRefreshHistoryData];
    };
    return footView;
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    // 滚动时，回收键盘
    [self.mySearchBar resignFirstResponder];
}
//#pragma mark - UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {

    [self saveSearchCacheAndRefreshView];
    if (searchBar.text.length == 0) return;
    NYSearchListViewController *ViewController = [NYSearchListViewController new];
    ViewController.searchString = searchBar.text;
    [self.navigationController pushViewController:ViewController animated:true];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {

}

/** 进入搜索状态调用此方法 */
- (void)saveSearchCacheAndRefreshView {

    QMUISearchBar *searchBar = self.mySearchBar;
    // 回收键盘
    [searchBar resignFirstResponder];
    // 先移除再刷新
    [self.searchMutaHistories removeObject:searchBar.text];
    [self.searchMutaHistories insertObject:searchBar.text atIndex:0];

    // 移除多余的缓存
    if (self.searchMutaHistories.count > self.searchHistoriesCount) {
        // 移除最后一条缓存
        [self.searchMutaHistories removeLastObject];
    }
    // 保存搜索信息
    [NSKeyedArchiver archiveRootObject:self.searchMutaHistories toFile:self.searchHistoriesCachePath];

    [self configRefreshHistoryData];
}


#pragma mark - Setter Getter Methods
- (QMUISearchBar *)mySearchBar {
    if (!_mySearchBar) {
        _mySearchBar = [[QMUISearchBar alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 65, 28)];
        _mySearchBar.qmui_placeholderColor    = UIColorMakeWithHex(@"#D0D0D0");
        _mySearchBar.qmui_textColor           = UIColorMakeWithHex(@"#333333");
        _mySearchBar.qmui_textField.backgroundColor    = UIColorMakeWithHex(@"#FFFFFF");
        _mySearchBar.qmui_textField.returnKeyType = UIReturnKeySearch;//变为搜索按钮
        _mySearchBar.placeholder = @"输入课程名称";
        _mySearchBar.delegate = self;
//        _mySearchBar.clipsToBounds = YES;
//        _mySearchBar.layer.cornerRadius = 14.0f;
        _mySearchBar.qmui_textField.backgroundColor    = UIColorMakeWithHex(@"#FFFFFF");
        _mySearchBar.qmui_textField.tintColor = UIColorMakeWithHex(@"#5396FF");
    }
    return _mySearchBar;
}
- (QMUIButton *)cancelButton {
    if (!_cancelButton) {
        _cancelButton = [[QMUIButton alloc] qmui_initWithImage:nil title:@"取消"];
        _cancelButton.frame = CGRectMake(0, 0, 40, 40);
        [_cancelButton setTitleColor:[UIColor whiteColor] forState:0];
        _cancelButton.titleLabel.font = UIFontMake(14);
        [_cancelButton addTarget:self action:@selector(popViewControllerAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cancelButton;
}
- (NSMutableArray *)searchMutaHistories {
    
    if (!_searchMutaHistories) {
        self.searchHistoriesCachePath = NYSEARCH_SEARCH_HISTORY_CACHE_PATH;
        _searchMutaHistories = [NSMutableArray arrayWithArray:[NSKeyedUnarchiver unarchiveObjectWithFile:self.searchHistoriesCachePath]];
    }
    return _searchMutaHistories;
}
- (void)setSearchHistoriesCachePath:(NSString *)searchHistoriesCachePath {
    
    _searchHistoriesCachePath = [searchHistoriesCachePath copy];
    // 刷新
    self.searchMutaHistories = nil;
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
